

#import "BaseAlertView.h"

//全局信号量
dispatch_semaphore_t _globalInstancesLock;
//执行QUEUE的Name
char *QUEUE_NAME = "com.alert.queue";

//初始化 -- 借鉴YYWebImage的写法
static void _AlertViewInitGlobal() {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _globalInstancesLock = dispatch_semaphore_create(1);
    });
}

@implementation BaseAlertView

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:[UIScreen mainScreen].bounds];
    if (self){
        _AlertViewInitGlobal();
    }
    return self;
}

#pragma mark - public
- (void)show{
    //位于非主线程 不阻塞
    dispatch_async(dispatch_queue_create(QUEUE_NAME, DISPATCH_QUEUE_SERIAL), ^{
        //Lock
        dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
        //保证主线程UI操作
        dispatch_async(dispatch_get_main_queue(), ^{
            [[[UIApplication sharedApplication] keyWindow] addSubview:self];
        });
    });
}

- (void)showIndex:(NSInteger)index{

    //位于非主线程 不阻塞
//    dispatch_async(dispatch_queue_create(QUEUE_NAME, DISPATCH_QUEUE_SERIAL), ^{
//        //Lock
//        dispatch_semaphore_wait(_globalInstancesLock, DISPATCH_TIME_FOREVER);
//        //保证主线程UI操作
//        dispatch_async(dispatch_get_main_queue(), ^{
            [[[UIApplication sharedApplication] keyWindow] insertSubview:self atIndex:index];
//        });
//    });
}

- (void)dismiss
{
    dispatch_async(dispatch_queue_create(QUEUE_NAME, DISPATCH_QUEUE_SERIAL), ^{
        //Release Lock
        dispatch_semaphore_signal(_globalInstancesLock);

        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeFromSuperview];
        });
    });
}

+ (void)showAll{
    [[[UIApplication sharedApplication] keyWindow].subviews bk_each:^(UIView *obj) {
        if ([[obj class] isSubclassOfClass:[BaseAlertView class]]) {
            obj.hidden = NO;
        }
    }];
}

+ (void)hideAll{
    [[[UIApplication sharedApplication] keyWindow].subviews bk_each:^(UIView *obj) {
        if ([[obj class] isSubclassOfClass:[BaseAlertView class]]) {
            obj.hidden = YES;
        }
    }];
}

@end
